<template>
  <div>
    <el-dialog
      :title="title"
      width="600px"
      :visible.sync="visible"
      :before-close="handleClose"
      :destroy-on-close="true"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
    >
      <el-form ref="ruleForm" :model="ruleForm" :rules="rules" label-width="100px" style="padding-right: 25px">
        <el-form-item label="名称" prop="deviceName">
          <el-input v-model="ruleForm.deviceName" :disabled="title !== '新增设备'" />
        </el-form-item>
        <el-form-item label="统计类型" prop="statisticalType">
          <el-select
            v-model="ruleForm.statisticalType"
            :disabled="title !== '新增设备'"
            style="width: 100%"
            placeholder="请选择统计类型"
            @change="ruleForm.unit = 1"
          >
            <el-option
              v-for="item in statisticalTypeList"
              :key="item.value"
              :label="item.text"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="统计值" prop="statisticalValue">
          <el-input v-model="ruleForm.statisticalValue" placeholder="请输入统计初始值，默认为0">
            <!--循环次数：次 作业量：吨/万吨 更换时间运行时间都是 小时/天/月/年 h/d/m/y ，显示英文-->
            <template v-if="Number(ruleForm.statisticalType) === 1" slot="append">次</template>
            <el-select
              v-if="ruleForm.statisticalType > 1"
              slot="append"
              v-model="ruleForm.unit"
              :disabled="title !== '新增设备'"
              style="width: 80px"
            >
              <el-option
                v-for="item in statisticalValueTypeList"
                :key="item.value"
                :label="item.text"
                :value="item.value"
              />
            </el-select>
          </el-input>
        </el-form-item>
        <el-form-item v-if="Number(ruleForm.statisticalType) === 4" label="关联字段" prop="factorCodeList">
          <el-select v-model="ruleForm.factorCodeList" :disabled="title !== '新增设备'" multiple placeholder="请选择关联字段" style="width: 100%">
            <el-option
              v-for="item in options"
              :key="item.value"
              :label="item.text"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="理论寿命" prop="theoreticalLifespan">
          <el-input v-model="ruleForm.theoreticalLifespan" />
        </el-form-item>
        <el-form-item :label="title === '新增设备' ? '新增时间' : '更换时间'" prop="deviceReplacementTime">
          <el-date-picker
            v-model="ruleForm.deviceReplacementTime"
            type="datetime"
            value-format="yyyy-MM-dd HH:mm:ss"
            placeholder="选择新增时间"
            :disabled="title === '修改设备'"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="一级预警" prop="firstLevelWarning">
          <el-input v-model.number="ruleForm.firstLevelWarning">
            <template slot="append">%</template>
          </el-input>
        </el-form-item>
        <el-form-item label="二级预警" prop="secondLevelWarning">
          <el-input v-model.number="ruleForm.secondLevelWarning">
            <template slot="append">%</template>
          </el-input>
        </el-form-item>
        <el-form-item label="品牌" prop="brand">
          <el-input v-model="ruleForm.brand" />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="ruleForm.remark" type="textarea" :rows="2" />
        </el-form-item>
<!--        <el-form-item v-if="title === '更换设备'" label="负责人" prop="owner">-->
<!--          <el-input v-model="ruleForm.owner" />-->
<!--        </el-form-item>-->
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button size="small" @click="handleClose">取 消</el-button>
        <el-button size="small" type="primary" :loading="loading" @click="submitForm('ruleForm')">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { saveDevice, queryDeviceDetailById, modifyDevice, replaceDevice } from '@/api/device'
import * as dayjs from 'dayjs'
import { queryDictList } from '@/api/dict'

export default {
  name: 'DeviceDialog',
  props: {
    visible: {
      required: true,
      type: Boolean,
      default: false
    },
    deviceInfo: {
      required: true,
      type: Object
    },
    deviceTreeId: {
      required: false,
      type: Number,
      default: undefined
    },
    title: {
      required: false,
      type: String,
      default: '新增设备'
    }
  },
  data() {
    return {
      options: [],
      statisticalTypeList: [],
      statisticalValueTypeList: [],
      ruleForm: {
        deviceName: '',
        deviceReplacementTime: '',
        firstLevelWarning: '',
        secondLevelWarning: '',
        theoreticalLifespan: '',
        brand: '',
        remark: '',
        statisticalType: undefined,
        statisticalValue: undefined,
        unit: 1,
        owner: undefined,
        factorCodeList: []
      },
      originStatisticalValue: null,
      rules: {
        deviceName: [
          { required: true, message: '请输入设备名称', trigger: 'blur' }
        ],
        deviceReplacementTime: [
          { required: true, message: '请选择新增时间', trigger: 'change' }
        ],
        statisticalType: [
          { required: true, message: '请选择统计类型', trigger: 'change' }
        ],
        statisticalValue: [
          { required: true, message: '请输入统计初始值，默认为0', trigger: 'blur' },
          {
            pattern: /((^[1-9][0-9]{0,8})+(.?[0-9]{1,3})?$)|(^[0]+(.[0-9]{1,3})?$)/,
            message: '请输入正确格式数字，小数位不能超过3位',
            trigger: 'change'
          }
        ],
        factorCodeList: [
          { required: true, message: '请选择关联字段', trigger: 'change' }
        ],
        theoreticalLifespan: [
          { required: true, message: '请输入理论寿命值', trigger: 'blur' }
        ],
        firstLevelWarning: [
          { required: true, type: 'number', message: '请输入一级预警' },
          {
            pattern: /^(?:0|[1-9][0-9]?|100)$/,
            message: '请输入0到100的整数',
            trigger: 'change'
          }
        ],
        secondLevelWarning: [
          { required: true, type: 'number', message: '请输入二级预警' },
          {
            pattern: /^(?:0|[1-9][0-9]?|100)$/,
            message: '请输入0到100的整数',
            trigger: 'change'
          }
        ],
        brand: [
          { required: false }
        ],
        remark: [
          { required: false }
        ],
        owner: [
          { required: false }
        ]
      },
      loading: false,
      validateVisible: false
    }
  },
  watch: {
    'ruleForm.statisticalType': {
      handler(value) {
        if (this.visible) {
          this.getDictList(value, 'statisticalValueTypeList', true)
          if (Number(value) === 4) {
            // 关联字段
            this.getDictList(5, 'options')
          }
        }
      },
      immediate: true
    },
    deviceInfo: {
      handler(val) {
        if (val?.id) {
          this.getDeviceDetail(val.id)
        }
      },
      deep: true
    },
    visible: {
      handler(value) {
        if (value) {
          this.getDictList(0, 'statisticalTypeList', true)
        }
      }
    }
  },
  mounted() {
    // this.getDictList(0, 'statisticalTypeList')
  },
  methods: {
    handleClose() {
      this.resetForm('ruleForm')
      this.ruleForm.factorCodeList = []
      this.$emit('update:visible', false)
    },
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.submit()
        } else {
          return false
        }
      })
    },
    resetForm(formName) {
      this.$refs[formName].resetFields()
    },
    submit() {
      this.loading = true
      if (this.title === '新增设备') {
        saveDevice({
          ...this.ruleForm,
          firstLevelWarning: this.ruleForm.firstLevelWarning ? this.ruleForm.firstLevelWarning / 100 : this.ruleForm.firstLevelWarning,
          secondLevelWarning: this.ruleForm.secondLevelWarning ? this.ruleForm.secondLevelWarning / 100 : this.ruleForm.secondLevelWarning,
          deviceTreeId: this.deviceTreeId
        }).then(({ success }) => {
          if (success) {
            this.$message.success('新增成功')
            this.$emit('onSuccess', 1)
            this.handleClose()
          }
        }).finally(() => {
          this.loading = false
        })
      } else if (this.title === '修改设备') {
        modifyDevice({
          id: this.deviceInfo.id,
          theoreticalLifespan: this.ruleForm.theoreticalLifespan,
          statisticalValue: this.originStatisticalValue === this.ruleForm.statisticalValue ? null : this.ruleForm.statisticalValue,
          firstLevelWarning: this.ruleForm.firstLevelWarning ? this.ruleForm.firstLevelWarning / 100 : this.ruleForm.firstLevelWarning,
          secondLevelWarning: this.ruleForm.secondLevelWarning ? this.ruleForm.secondLevelWarning / 100 : this.ruleForm.secondLevelWarning,
          brand: this.ruleForm.brand,
          remark: this.ruleForm.remark
        }).then(({ success }) => {
          if (success) {
            this.$message.success('修改成功')
            this.$emit('onSuccess')
            this.handleClose()
          }
        }).finally(() => {
          this.loading = false
        })
      } else {
        replaceDevice({
          id: this.deviceInfo.id,
          theoreticalLifespan: this.ruleForm.theoreticalLifespan,
          deviceReplacementTime: this.ruleForm.deviceReplacementTime,
          statisticalValue: this.ruleForm.statisticalValue,
          firstLevelWarning: this.ruleForm.firstLevelWarning ? this.ruleForm.firstLevelWarning / 100 : this.ruleForm.firstLevelWarning,
          secondLevelWarning: this.ruleForm.secondLevelWarning ? this.ruleForm.secondLevelWarning / 100 : this.ruleForm.secondLevelWarning,
          brand: this.ruleForm.brand,
          remark: this.ruleForm.remark,
          owner: this.ruleForm.owner
        }).then(({ success }) => {
          if (success) {
            this.$message.success('更换成功')
            this.$emit('onSuccess')
            this.handleClose()
          }
        }).finally(() => {
          this.loading = false
        })
      }
    },
    getDeviceDetail(id) {
      queryDeviceDetailById({
        id
      }).then(({ data, success }) => {
        if (success) {
          this.ruleForm.deviceName = data.deviceName
          this.ruleForm.theoreticalLifespan = data.theoreticalLifespan
          this.ruleForm.unit = data.unit
          this.ruleForm.statisticalType = data.statisticalType
          this.ruleForm.brand = data.brand
          this.ruleForm.firstLevelWarning = data.firstLevelWarning ? data.firstLevelWarning * 100 : data.firstLevelWarning
          this.ruleForm.secondLevelWarning = data.secondLevelWarning ? data.secondLevelWarning * 100 : data.secondLevelWarning
          this.ruleForm.remark = data.remark
          this.ruleForm.factorCodeList = data.factorCodeList
          if (this.title === '修改设备') {
            this.ruleForm.deviceReplacementTime = data.deviceReplacementTime
            this.ruleForm.statisticalValue = data.statisticalValue
            this.originStatisticalValue = data.statisticalValue
          }
          if (this.title === '更换设备') {
            this.ruleForm.deviceReplacementTime = dayjs().format('YYYY-MM-DD HH:mm:ss')
            this.ruleForm.statisticalValue = 0
          }
        }
      })
    },
    getDictList(dictType, field, convert = false) {
      queryDictList({ dictType }).then(({ data, success }) => {
        if (success) {
          this[field] = (data || []).map(item => {
            return {
              text: item.text,
              value: convert ? Number(item.value) : item.value
            }
          })
          if (field === 'statisticalTypeList' && this.title !== '新增设备') {
            this[field].push({
              text: '循环次数',
              value: 1
            })
          }
        }
      })
    }
  }
}
</script>

<style scoped>

</style>
